
/**
** \file       else_clause.c
**
** \brief      this function parse the else_clause rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse, De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    1.0
**
** \date       28 Novembre 2010
**
*/

#include "rules.h"

static struct else_clause        *opt_ecl(struct else_clause     *eclause)
{
  eclause->in_then = calloc(1, sizeof (s_cmpdlist));

  if (g_data->lexer == NULL || rule_compound_list(eclause->in_then) == NULL)
  {
    free_cmpdlist(eclause->in_if);
    eclause->in_if = NULL;

    free(eclause->in_then);
    eclause->in_then = NULL;

    return (NULL);
  }

  eclause->else_clause = calloc(1, sizeof (struct else_clause));

  if (g_data->lexer == NULL || rule_else_clause(eclause->else_clause) == NULL)
  {
    free(eclause->else_clause);
    eclause->else_clause = NULL;
  }

  return (eclause);
}

static struct else_clause     *elif(struct else_clause         *eclause)
{
  if (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "elif") == 0)
    g_data->lexer = g_data->lexer->next;
  else
    return (NULL);

  eclause->in_if = calloc(1, sizeof (s_cmpdlist));

  if (g_data->lexer == NULL || rule_compound_list(eclause->in_if) == NULL)
  {
    free(eclause->in_if);
    eclause->in_if = NULL;

    return (NULL);
  }

  if (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "then") == 0)
    g_data->lexer = g_data->lexer->next;
  else
  {
    free(eclause->in_if);
    eclause->in_if = NULL;

    return (NULL);
  }

  return (opt_ecl(eclause));
}

struct else_clause           *rule_else_clause(struct else_clause    *eclause)
{
  if (g_data->lexer == NULL)
    return (NULL);

  if (strcmp(g_data->lexer->token->id, "else") == 0)
  {
    g_data->lexer = g_data->lexer->next;

    if (g_data->lexer == NULL)
      return (NULL);

    eclause->in_else = calloc(1, sizeof (s_cmpdlist));

    if (rule_compound_list(eclause->in_else) == NULL)
    {
      free(eclause->in_else);
      eclause->in_else = NULL;

      return (NULL);
    }

    return (eclause);
  }
  else
    return (elif(eclause));
}
